<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import type {TableColumnsType, TableProps} from 'ant-design-vue'
import {Modal} from 'ant-design-vue'
import dayjs from 'dayjs'
import {useAuthStore} from '@/stores/modules/auth'
import {userApi} from '@/api'
import type {UserVO} from '@/types/vo/user'
import {handleError, success} from '@/utils/message'
import {USER} from '@/constants/messages'

const authStore = useAuthStore()

const loading = ref(false)
const detailModalVisible = ref(false)
const userList = ref<UserVO[]>([])
const selectedUser = ref<UserVO | null>(null)

const searchParams = reactive({
  userAccount: '',
  userName: '',
  userRole: undefined as string | undefined,
  userStatus: undefined as number | undefined
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns: TableColumnsType = [
  {title: '头像', key: 'userAvatar', width: 80},
  {title: '账号', dataIndex: 'userAccount', key: 'userAccount'},
  {title: '昵称', dataIndex: 'userName', key: 'userName'},
  {title: '邮箱', dataIndex: 'email', key: 'email'},
  {title: '角色', key: 'userRole', width: 100},
  {title: '状态', key: 'userStatus', width: 80},
  {title: '注册时间', key: 'createTime', width: 180},
  {title: '操作', key: 'action', width: 150, fixed: 'right'}
]

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const result = await userApi.list({
      current: pagination.current,
      size: pagination.pageSize,
      ...searchParams
    })
    userList.value = result.records
    pagination.total = result.total
  } catch (error: any) {
    handleError(error, USER.LOAD_FAILED)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadUsers()
}

// 表格变化
const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  loadUsers()
}

// 查看用户详情
const viewUser = (user: UserVO) => {
  selectedUser.value = user
  detailModalVisible.value = true
}

// 切换用户状态
const toggleUserStatus = (user: UserVO) => {
  const newStatus = user.userStatus === 1 ? 0 : 1
  const action = newStatus === 0 ? '禁用' : '启用'

  Modal.confirm({
    title: `确认${action}用户`,
    content: `确定要${action}用户 "${user.userAccount}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await userApi.updateStatus(user.id!, {userStatus: newStatus})
        success(`${action}成功`)
        loadUsers()
      } catch (error: any) {
        handleError(error, `${action}失败`)
      }
    }
  })
}

// 格式化日期
const formatDate = (date?: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

onMounted(() => {
  loadUsers()
})
</script>

<template>
  <div class="user-management-container">
    <a-card title="用户管理">
      <!-- 搜索筛选 -->
      <div class="search-section">
        <a-space>
          <a-input-search
              v-model:value="searchParams.userAccount"
              placeholder="搜索账号"
              style="width: 200px"
              @search="handleSearch"
          />
          <a-input-search
              v-model:value="searchParams.userName"
              placeholder="搜索昵称"
              style="width: 200px"
              @search="handleSearch"
          />
          <a-select
              v-model:value="searchParams.userRole"
              allowClear
              placeholder="选择角色"
              style="width: 120px"
              @change="handleSearch"
          >
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
          <a-select
              v-model:value="searchParams.userStatus"
              allowClear
              placeholder="选择状态"
              style="width: 120px"
              @change="handleSearch"
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-space>
      </div>

      <!-- 用户列表 -->
      <a-table
          :columns="columns"
          :data-source="userList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          style="margin-top: 16px"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userAvatar'">
            <a-avatar :src="record.userAvatar">
              {{ record.userName?.charAt(0) || 'U' }}
            </a-avatar>
          </template>

          <template v-if="column.key === 'userRole'">
            <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
              {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'userStatus'">
            <a-tag :color="record.userStatus === 1 ? 'green' : 'red'">
              {{ record.userStatus === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                  size="small"
                  type="link"
                  @click="viewUser(record)"
              >
                查看
              </a-button>
              <a-button
                  v-if="record.id !== authStore.user?.id"
                  :danger="record.userStatus === 1"
                  size="small"
                  type="link"
                  @click="toggleUserStatus(record)"
              >
                {{ record.userStatus === 1 ? '禁用' : '启用' }}
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 用户详情对话框 -->
    <a-modal
        v-model:open="detailModalVisible"
        :footer="null"
        title="用户详情"
        width="600px"
    >
      <a-descriptions v-if="selectedUser" :column="1">
        <a-descriptions-item label="头像">
          <a-avatar :size="64" :src="selectedUser.userAvatar">
            {{ selectedUser.userName?.charAt(0) || 'U' }}
          </a-avatar>
        </a-descriptions-item>
        <a-descriptions-item label="账号">
          {{ selectedUser.userAccount }}
        </a-descriptions-item>
        <a-descriptions-item label="昵称">
          {{ selectedUser.userName || '未设置' }}
        </a-descriptions-item>
        <a-descriptions-item label="邮箱">
          {{ selectedUser.email || '未绑定' }}
        </a-descriptions-item>
        <a-descriptions-item label="个人简介">
          {{ selectedUser.userProfile || '暂无' }}
        </a-descriptions-item>
        <a-descriptions-item label="角色">
          <a-tag :color="selectedUser.userRole === 'admin' ? 'red' : 'blue'">
            {{ selectedUser.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="selectedUser.userStatus === 1 ? 'green' : 'red'">
            {{ selectedUser.userStatus === 1 ? '正常' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="注册时间">
          {{ formatDate(selectedUser.createTime) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.user-management-container {
  // 容器样式由 AdminLayout 管理
}

.search-section {
  margin-bottom: 16px;
}
</style>